import React, { useEffect, useState, useRef } from "react";
import {
    StyleSheet,
    View,
    Text,
    Keyboard,
    TouchableWithoutFeedback,
    TouchableOpacity,
    TextInput,
    Platform
} from 'react-native';
import {router, Stack,} from "expo-router";
import useCountdown from "@/hooks/useCountdown"
import {AppDispatch, RootState} from "@/store";
import {useDispatch, useSelector} from "react-redux";
import { showToast} from "@/utils/rootToast"
import { sendLoginCode, postLogin } from '@/services/login';
import { setTokenInfo, getUserInfoDetail } from "@/store/slices/loginSlice"
import {setImStorgeToken, setStorgeToken} from "@/utils/index"
import { loadingService} from "@/utils/loadingServer";
import {
    CodeField,
    Cursor,
    useBlurOnFulfill,
    useClearByFocusCell,
} from 'react-native-confirmation-code-field';

import NavBack from "@/components/navBack/index";

const CELL_COUNT = 4;


export default function verifyCodeScreen() {
    const [code, setCode] = useState(['', '', '', '']);
    const inputs = useRef([]);
    const { seconds, isCounting, startCountdown, resetCountdown } = useCountdown();
    const login = useSelector((state: RootState) => state.login);

    const [value, setValue] = useState('');
    const ref = useBlurOnFulfill({value, cellCount: CELL_COUNT});
    const [props, getCellOnLayoutHandler] = useClearByFocusCell({
        value,
        setValue,
    });


    const dispatch = useDispatch<AppDispatch>();

    useEffect(() => {
        handleGetCode();

    }, [])

    useEffect(() => {
    }, []);


    const handleGetCode = () => {
        // 实际的验证码获取逻辑（如 API 调用）应该放在这里

        const phone = login.phone;
        sendLoginCode(phone)
            .then(res => {
                showToast("验证码已发送");
                console.log('res', res);
            })
            .catch(err => {
                console.log('err', err);
            })

        startCountdown();
    };

    const handleChange = (text, index) => {
        const newCode = [...code];
        newCode[index] = text;
        setCode(newCode);

        if (text && index < 3) {
            // Move focus to next input行·
            inputs.current[index + 1].focus();
        }

        if (text && index >= 3) {
            const data = {
                ...login.loginInfo,
                code: code.join("") + text,
            };

            loadingService.show();
            postLogin(data)
                .then(res => {
                    console.log('res', res);
                    dispatch(setTokenInfo(res.data))
                    const token = res.data.token;
                    setStorgeToken(token);
                    loadingService.hide();
                    showToast("登陆成功");
                    router.replace("/")
                    dispatch(getUserInfoDetail())
                })
                .catch(err => {
                    console.log('err', err);
                    showToast(err.data.msg);
                    loadingService.hide();
                })
        }

        console.log("index", index);
    };

    const handleKeyPress = (key, index) => {
        if (key === 'Backspace') {
            const newCode = [...code];
            newCode[index] = '';
            setCode(newCode);

            if (index > 0) {
                // Move focus to previous input
                inputs.current[index - 1].focus();
            }
        }
    };

    const handleFocus = index => {
        // Scroll to the focused input
        inputs.current[index].focus();
    };

    const postViftyCode = function (val: string) {
        setValue(val);
        if (val.length >= 4) {
            const data = {
                ...login.loginInfo,
                code: val
            };
            console.log('data', data);
            loadingService.show();
            postLogin(data)
                .then(res => {
                    console.log('res', res);
                    dispatch(setTokenInfo(res.data))
                    const token = res.data.token;
                    const imToken = res.data.imToken;
                    setStorgeToken(token);
                    setImStorgeToken(imToken);
                    loadingService.hide();
                    showToast("登陆成功");
                    router.replace("/")
                    dispatch(getUserInfoDetail())
                })
                .catch(err => {
                    console.log('err', err);
                    loadingService.hide();
                    setValue("");
                    showToast("验证码不正确");


                })
        };
    };


    return (
        <View style={{ backgroundColor: "#fff", height: "100%" }}>
            <Stack.Screen
                options={{
                    headerShown: false,
                }}
            />
            <NavBack title={""} />

            <Text style={styles.verifyTitle}>输入验证码</Text>
            <Text style={styles.verifyNumber}>验证码已发送至{ login.phone }</Text>
            <View style={{ marginTop: 39, paddingHorizontal: 29, }}>

                <CodeField
                    ref={ref}
                    {...props}
                    // Use `caretHidden={false}` when users can't paste a text value, because context menu doesn't appear
                    value={value}
                    onChangeText={postViftyCode}
                    cellCount={CELL_COUNT}
                    rootStyle={styles.codeFieldRoot}
                    keyboardType="number-pad"
                    textContentType="oneTimeCode"
                    autoComplete={Platform.select({ android: 'sms-otp', default: 'one-time-code' })}
                    testID="my-code-input"
                    renderCell={({index, symbol, isFocused}) => (
                        <Text
                            key={index}
                            style={[styles.input, isFocused && styles.focusCell]}
                            onLayout={getCellOnLayoutHandler(index)}>
                            {symbol || (isFocused ? <Cursor/> : null)}
                        </Text>
                    )}
                />

                {/*<TouchableWithoutFeedback onPress={Keyboard.dismiss}>*/}
                {/*    <View style={styles.container}>*/}
                {/*        <View style={styles.inputContainer}>*/}
                {/*            {code.map((value, index) => (*/}
                {/*                <TextInput*/}
                {/*                    key={index}*/}
                {/*                    ref={ref => inputs.current[index] = ref}*/}
                {/*                    style={styles.input}*/}
                {/*                    keyboardType="number-pad"*/}
                {/*                    maxLength={1}*/}
                {/*                    value={value}*/}
                {/*                    onChangeText={text => handleChange(text, index)}*/}
                {/*                    onKeyPress={({ nativeEvent }) => handleKeyPress(nativeEvent.key, index)}*/}
                {/*                    onFocus={() => handleFocus(index)}*/}
                {/*                />*/}
                {/*            ))}*/}
                {/*        </View>*/}
                {/*    </View>*/}
                {/*</TouchableWithoutFeedback>*/}
            </View>
            {
                isCounting ? (
                    <TouchableOpacity
                        activeOpacity={1}
                        style={styles.reGetCode}
                    >
                        <Text style={{ color: "#9C9EAC" }}>{ seconds }秒后再次发送验证码</Text>
                    </TouchableOpacity>
                ) : (
                    <TouchableOpacity
                        activeOpacity={1}
                        onPress={handleGetCode}
                        style={styles.reGetCode}
                    >
                        <Text style={{ color: "#EC6138"}}>重新获取验证码</Text>
                    </TouchableOpacity>

                )
            }
        </View>
    );
}

const styles = StyleSheet.create({
    verifyTitle: {
        marginTop: 124,
        fontWeight: "bold",
        color: "#2A2B30",
        fontSize: 24,
        marginLeft: 24,
    },
    verifyNumber: {
        marginTop: 10,
        color: "#2A2B30",
        fontSize: 14,
        marginLeft: 24,
        letterSpacing: 1,
    },
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        paddingLeft: 29,
        paddingRight: 29,
    },
    titles: {
        fontSize: 18,
        marginBottom: 20,
    },
    inputContainer: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        width: '100%',
    },
    input: {
        width: 62,
        height: 62,
        backgroundColor: "#F3F3F3",
        borderRadius: 10,
        textAlign: 'center',
        fontSize: 26,
        color: "#2A2B30",
        flexDirection: "row",
        alignItems: "center",
        lineHeight: 62,
        overflow: "hidden",
    },
    getCode: {
        fontSize: 14,
        color: "#9C9EAC",
        marginTop: 94,
        marginLeft: 29,
    },
    reGetCode: {
        fontSize: 14,
        marginTop: 30,
        marginLeft: 29,
    },
    root: {flex: 1, padding: 20},
    title: {textAlign: 'center', fontSize: 30},
    codeFieldRoot: {marginTop: 20},
    cell: {
        width: 40,
        height: 40,
        lineHeight: 38,
        fontSize: 24,
        borderWidth: 2,
        borderColor: '#00000030',
        textAlign: 'center',
    },
    focusCell: {
        borderColor: '#EC6138',
        borderWidth: 1
    },
});
